<template>
  <el-card style="height: 70px; margin-bottom: 10px">
    <el-form class="form" :inline="true">
      <el-form-item label="用户名:">
        <el-input
          placeholder="请输入搜索的用户名"
          clearable
          v-model="rolename"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="search">搜索</el-button>
        <el-button plain @click="reset">重置</el-button>
      </el-form-item>
    </el-form>
  </el-card>
  <el-card>
    <el-button type="primary" @click="addUser" icon="Plus">添加角色</el-button>
    <el-table border style="margin: 10px 0px" :data="tableData">
      <el-table-column type="index" label="#" width="80px"></el-table-column>
      <el-table-column label="ID" prop="id"></el-table-column>
      <el-table-column
        label="角色名字"
        prop="roleName"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column
        label="创建时间"
        prop="createTime"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column
        label="更新时间"
        prop="updateTime"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column label="操作" width="320px" align="center">
        <template #="{ row }">
          <el-button type="primary" icon="Plus" @click="setPermission(row)">
            分配权限
          </el-button>
          <el-button type="primary" icon="Edit" @click="editUser(row)">
            编辑
          </el-button>
          <el-button type="primary" icon="Delete" @click="deleteUser(row.id)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      v-model:current-page="pageNo"
      v-model:page-size="limit"
      :page-sizes="[10, 20, 30, 40]"
      :background="true"
      layout="prev, pager, next, jumper,->,sizes, total,"
      :total="total"
      @current-change="getDataList"
      @size-change="handler"
    />
    <!-- 添加和编辑 -->
    <el-dialog
      v-model="dialogFormVisible"
      :title="RoleParams.id ? '编辑' : '添加'"
    >
      <el-form :model="RoleParams" :rules="rules" ref="formRef">
        <el-form-item label="角色名称" prop="roleName">
          <el-input
            v-model="RoleParams.roleName"
            placeholder="请输入角色名称"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="save">确定</el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 分配权限 -->
    <el-drawer v-model="drawer">
      <template #header>
        <h4>分配权限</h4>
      </template>
      <template #default>
        <el-tree
          ref="tree"
          :data="menuArr"
          show-checkbox
          node-key="id"
          default-expand-all
          :default-checked-keys="selectArr"
          :props="defaultProps"
        />
      </template>
      <template #footer>
        <div style="flex: auto">
          <el-button @click="drawer = false">取消</el-button>
          <el-button type="primary" @click="confirmPermission">确定</el-button>
        </div>
      </template>
    </el-drawer>
  </el-card>
</template>
<script setup lang="ts">
import { reactive, ref, nextTick } from 'vue'
import useLayOutSettingStore from '@/store/modules/setting'
import {
  reqAllRoleList,
  reqAddOrUpdateRole,
  reqRemoveRole,
  reqAllMenuList,
  reqSetPermission,
} from '@/api/acl/role'
import type {
  RoleResponseData,
  Records,
  RoleData,
  MenuResponseData,
  MenuList,
} from '@/api/acl/role/type'
import { ElMessage } from 'element-plus'
let settingStore = useLayOutSettingStore()
const pageNo = ref<number>(1)
const limit = ref<number>(10)
const total = ref(0)
const tableData = ref<Records>([])
const rolename = ref<string>('')
const dialogFormVisible = ref<boolean>(false)
const formRef = ref()
const drawer = ref<boolean>(false)
const menuArr = ref<MenuList>([])
const RoleParams = reactive<RoleData>({
  roleName: '',
})
const rules = {
  roleName: [
    { required: true, message: '角色名称不能空', trigger: 'blur' },
    { min: 2, message: '角色名称至少2位', trigger: 'blur' },
  ],
}
const defaultProps = {
  children: 'children',
  label: 'name',
}
const selectArr = ref<number[]>([])
const tree = ref()

// 获取列表
const getDataList = async (pager = 1) => {
  pageNo.value = pager
  const res: RoleResponseData = await reqAllRoleList(
    pageNo.value,
    limit.value,
    rolename.value,
  )
  if (res.code == 200) {
    tableData.value = res.data.records
    total.value = res.data.total
  }
}
getDataList()

// 刷新
const search = () => {
  getDataList()
  // username.value = ''
}
// 重置
const reset = () => {
  settingStore.refsh = !settingStore.refsh
}
// 分页
const handler = () => {
  getDataList()
}
// 添加角色
const addUser = () => {
  dialogFormVisible.value = true
  Object.assign(RoleParams, {
    roleName: '',
    id: '',
  })
  nextTick(() => {
    formRef.value.clearValidate('roleName')
  })
}
// 分配权限
const setPermission = async (row: RoleData) => {
  drawer.value = true
  Object.assign(RoleParams, row)

  const res: MenuResponseData = await reqAllMenuList(row.id as number)
  if (res.code == 200) {
    menuArr.value = res.data
    selectArr.value = filterSelectArr(menuArr.value, [])
  }
}
const filterSelectArr = (allData: any, initArr: any) => {
  allData.forEach((item: any) => {
    if (item.select && item.level === 4) {
      initArr.push(item.id)
    }
    if (item.children && item.children.length > 0) {
      filterSelectArr(item.children, initArr)
    }
  })
  return initArr
}
// 分配权限的确定
const confirmPermission = async () => {
  let roleId = RoleParams.id as number
  let arr = tree.value.getCheckedKeys()
  let arr1 = tree.value.getHalfCheckedKeys()
  let permissionId = arr.concat(arr1)
  const res: any = await reqSetPermission(roleId, permissionId)
  if (res.code == 200) {
    ElMessage({
      type: 'success',
      message: '分配权限成功',
    })
    drawer.value = false
    window.location.reload()
  }
}
// 编辑
const editUser = (row: RoleData) => {
  dialogFormVisible.value = true
  Object.assign(RoleParams, row)
  nextTick(() => {
    formRef.value.clearValidate('roleName')
  })
}
// 确定
const save = async () => {
  await formRef.value.validate()

  const res = await reqAddOrUpdateRole(RoleParams)
  if (res.code == 200) {
    ElMessage({
      type: 'success',
      message: RoleParams.id ? '修改成功' : '添加成功',
    })
    dialogFormVisible.value = false
    getDataList(RoleParams.id ? pageNo.value : 1)
  } else {
  }
}
// 删除
const deleteUser = async (id: number) => {
  const res: any = await reqRemoveRole(id)
  if (res.code == 200) {
    ElMessage({
      type: 'success',
      message: '删除成功',
    })
    getDataList(tableData.value.length > 1 ? pageNo.value : pageNo.value - 1)
  }
}
</script>
<style scoped lang="scss">
.form {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
